<template>
  <el-dialog
    v-model="visible"
    title="修改部门归属"
    width="600px"
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="当前部门">
        <el-input :value="currentDepartment?.name || '-'" disabled />
        <div class="form-tip">当前已确认的部门</div>
      </el-form-item>
      <el-form-item label="新部门" prop="new_department">
        <el-input
          v-model="form.new_department"
          placeholder="请输入新的部门ID或部门名称"
        />
        <div class="form-tip">请输入新的部门ID（如：dept_003）或部门名称</div>
      </el-form-item>
      <el-form-item label="修改原因" prop="change_reason">
        <el-input
          v-model="form.change_reason"
          type="textarea"
          :rows="4"
          placeholder="请输入修改原因（必填）"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">
        提交
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { updateDepartment } from "../../../servers";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  assetId: { type: Number, default: null },
  currentDepartment: {
    type: Object,
    default: () => null,
  },
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "success"): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const formRef = ref();
const submitting = ref(false);
const form = ref({
  new_department: "",
  change_reason: "",
});

const rules = {
  new_department: [
    { required: true, message: "请输入新的部门", trigger: "blur" },
  ],
  change_reason: [
    { required: true, message: "请输入修改原因", trigger: "blur" },
  ],
};

// 监听弹窗打开，初始化表单
watch(visible, (newVal) => {
  if (newVal) {
    form.value.new_department = "";
    form.value.change_reason = "";
  }
});

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;

    submitting.value = true;
    try {
      await updateDepartment(props.assetId!, {
        new_department: form.value.new_department,
        change_reason: form.value.change_reason,
      });
      ElMessage.success("部门归属已更新");
      emit("success");
      emit("update:modelValue", false);
    } catch (error: any) {
      ElMessage.error(error?.message || "修改部门失败");
    } finally {
      submitting.value = false;
    }
  });
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};
</script>

<style scoped lang="scss">
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>

